#include <iocc2530.h>
#include "hal_mcu.h"
#include "hal_assert.h"
#include "hal_board.h"
#include "hal_rf.h"
#include "basic_rf.h"
#include <stdio.h>
#include "info.h"
#include "uart1.h"
#include "string.h"

#define RF_CHANNEL            15                                // 2.4 GHz RF channel
#define PAN_ID                0x2002
#define SEND_ADDR             0x2530
#define RECV_ADDR             0xffff

#define NODE1 1
#define NODE2 2
#define NODE3 3
#define NODE_TYPE             1                                 //
#define NODE NODE1

int uart0_recv_char(void);
extern char recvBuf[256];
extern int recvCnt;

void io_init(void)
{
  P2SEL &= ~0x01;
  P2DIR &= ~0x01;
}

static basicRfCfg_t basicRfConfig;
int ledstatus = 0;
void rfSendData(void)
{
    recvBuf[recvCnt++]=uart0_recv_char();
    uint8 pTxData[100];
    strcpy(pTxData, recvBuf);
    // Keep Receiver off when not needed to save power
    basicRfReceiveOff();
    while (TRUE){
      hal_led_on(1);
      basicRfSendPacket(RECV_ADDR,pTxData,sizeof pTxData);
    }
}

void rfRecvData(void)
{
  uint8 pRxData[128];
  int rlen;
   basicRfReceiveOn();           
    // Main loop
    while (TRUE) {
        while(!basicRfPacketIsReady());
        rlen = basicRfReceive(pRxData, sizeof pRxData, NULL);
        if(rlen > 0 ) {
          
          if (NODE1==NODE) {
            if(strcmp(pRxData,"LED6 is on")){
                hal_led_on(1);
                printf("{data=LED is on}");
            }
          } else {
             hal_led_off(1);
             printf("{data=LED is off}");
          }
          
          if (NODE2==NODE) {
            if(strcmp(pRxData,"LED8 is on")){
                hal_led_on(1);
                printf("{data=LED is on}");
            }
          } else {
             hal_led_off(1);
             printf("{data=LED is off}");
          }
          
          if (NODE3==NODE) {
            if(strcmp(pRxData,"LED10 is on")){
                hal_led_on(1);
                printf("{data=LED is on}");
            }
          } else {
             hal_led_off(1);
             printf("{data=LED is off}");
          }
        }
    }
}

void main(void)
{
    halMcuInit();

    io_init();
    
    hal_led_init();
    
    uart0_init(0x00,0x00);
    
    hal_uart_init();
    
    //lcd_dis();
    
    if (FAILED == halRfInit()) {
        HAL_ASSERT(FALSE);
    }

    // Config basicRF
    basicRfConfig.panId = PAN_ID;
    basicRfConfig.channel = RF_CHANNEL;
    basicRfConfig.ackRequest = TRUE;
#ifdef SECURITY_CCM
    basicRfConfig.securityKey = key;
#endif

    
    // Initialize BasicRF
#if NODE_TYPE
    basicRfConfig.myAddr = SEND_ADDR;
#else
    basicRfConfig.myAddr = RECV_ADDR; 
#endif
    
    if(basicRfInit(&basicRfConfig)==FAILED) {
      HAL_ASSERT(FALSE);
    }
#if NODE_TYPE
  rfSendData();
#else
  rfRecvData();   
#endif
}
